import React from 'react'
import CategoryTCss from './index.module.scss'
import { Link, withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import GoodsBag from '../../components/GoodsBag'
import back from '../../js/goBack'
import { CategoryServer, HomeServer } from '../../api/index'

class CategoryT extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            navList: [
                {
                    "title": "综合",
                    "icon": "",
                    "isSelected": true,
                    "click": 0
                },
                {
                    "title": "价格",
                    "isSelected": false,
                    "click": 0
                },
                {
                    "title": "销量",

                    "isSelected": false,
                    "click": 0
                },
                {
                    "title": "筛选",

                    "isSelected": false,
                    "click": 0
                }
            ], //导航列表
            priceCli: 0, //价格当前筛选
            typeGoodsList: [], //分类数据
            thisGoodsList: [], //当前分类数据
            headerTop: true, //返回顶部显隐
            searchValue: "", //搜索框数据
            isScreen: false, //是否筛选
            screenData: [], //筛选数据
        }
    }
    render() {
        return (
            <div id="top" className={CategoryTCss.main}>
                {/* 返回顶部 */}
                <div className={this.state.headerTop ? CategoryTCss.toTop : CategoryTCss.toTop + " " + CategoryTCss.toTopShow}>
                    <div>
                        <i className="iconfont icon-icon_phone"></i>
                        <p>App下载</p>
                    </div>
                    <span>
                        <Link to="/cart">
                            <i className={"iconfont icon-icon_gwcq " + CategoryTCss.firsti}></i>
                        </Link>
                    </span>
                    <span onClick={() => this.scrollToAnchor('top')}>
                        <i className="iconfont icon-icon_hd"></i>
                    </span>

                </div>
                {/* 头部 */}
                <div className={CategoryTCss.header}>
                    <div className={CategoryTCss.search}>
                        <i onClick={this.goBack} className={"iconfont icon-btn_backx " + CategoryTCss.back}></i>
                        <div className={CategoryTCss.searchBox}>
                            <i className="iconfont icon-icon_ssx"></i>
                            <input onChange={e => this.inputValChange(e)} value={this.state.searchValue} type="text" placeholder='搜索/商品/品牌/类别' />
                            {
                                this.state.searchValue ? <img onClick={this.clearSearch} src="https://m.vsigo.cn/static/img/icon-delete.png" alt="" /> : <p></p>
                            }

                        </div>
                        <p>搜索</p>
                    </div>
                    <ul className={CategoryTCss.typeBox}>
                        {
                            this.state.navList.map((item, index) => {
                                return (
                                    <li onClick={this.navChange.bind(this, { nav: item.title, par: this.state.priceCli })} className={item.isSelected ? CategoryTCss.liChange : ''} key={index}>
                                        <p>{item.title}</p>
                                        {
                                            item.title === "价格" && <div>
                                                <i className={this.state.priceCli === 1 ? 'iconfont icon-icon_XS_sx ' + CategoryTCss.iChange : 'iconfont icon-icon_XS_sx'}></i>
                                                <i className={this.state.priceCli === 2 ? 'iconfont icon-iocn_xx_nx ' + CategoryTCss.iChange : 'iconfont icon-iocn_xx_nx'}></i>
                                            </div>
                                        }
                                    </li>
                                )
                            })
                        }
                    </ul>
                </div>
                {/* 内容 */}
                <div className={CategoryTCss.content}>
                    {
                        this.state.thisGoodsList.length > 0 ?
                            this.state.thisGoodsList.map((item, index) => {
                                return (
                                    <Link className={CategoryTCss.sellersList} to={'/deatil/'+item.ItemID} key={index}>
                                        <GoodsBag {...item}></GoodsBag>
                                    </Link>
                                )
                            }) :
                            <div className={CategoryTCss.scrNull}>
                                <div>
                                    <img src="https://m.vsigo.cn/static/img/icon_sswjg.png" alt="" />
                                </div>
                                <p>暂无搜索结果，换个词试试吧</p>
                            </div>
                    }
                </div>
                {/* 筛选框 */}
                <div className={this.state.isScreen ? CategoryTCss.screenBox + " " + CategoryTCss.scrBoxHide : CategoryTCss.screenBox}>
                    <div onClick={this.screenChange.bind(this, { par: "HIDE" })} className={CategoryTCss.scrBottomHide}></div>
                    {/* 选择框 */}
                    <div className={CategoryTCss.screen}>
                        {/* 筛选内容 */}
                        <ul className={CategoryTCss.scrTop}>
                            {
                                this.state.screenData.map((item) => {
                                    return (
                                        <li key={item.id} onClick={this.screenChange.bind(this, { par: "ONE", id: item.id })}>
                                            <div className={CategoryTCss.scrTitle}>
                                                <p>{item.title}</p>
                                                <i className={item.isChange ? CategoryTCss.scrIActive + " iconfont icon-btn_jrx" : " iconfont icon-btn_jrx"}></i>
                                            </div>
                                            {
                                                item.isChange ? <div className={CategoryTCss.scrList}>
                                                    {
                                                        item.checkbox ?
                                                            item.content.map((items, indexs) => {
                                                                return (
                                                                    <p onClick={this.screenChange.bind(this, { par: "TOW", id: item.id, title: items.title })} className={items.isChange ? CategoryTCss.scrActive : ''} key={indexs}>{items.title}</p>
                                                                )
                                                            })
                                                            :
                                                            item.content.map((items, indexs) => {
                                                                return (
                                                                    item.content.some((check) => {
                                                                        return check.isChange
                                                                    }) ?
                                                                        <p hidden={!items.isChange} onClick={this.screenChange.bind(this, { par: "TOW", id: item.id, title: items.title })} className={items.isChange ? CategoryTCss.scrActive : ''} key={indexs}>{items.title}</p>
                                                                        :
                                                                        <p onClick={this.screenChange.bind(this, { par: "TOW", id: item.id, title: items.title })} className={items.isChange ? CategoryTCss.scrActive : ''} key={indexs}>{items.title}</p>
                                                                )
                                                            })
                                                    }
                                                </div> : ''
                                            }
                                        </li>
                                    )
                                })
                            }
                        </ul>
                        {/* 底部按钮 */}
                        <div className={CategoryTCss.scrBtn}>
                            <p onClick={this.screenChange.bind(this, { par: "CLEAR" })}>重置</p>
                            <p onClick={this.screenChange.bind(this, { par: "SCR" })}>筛选({this.state.thisGoodsList.length})</p>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
    // 导航栏选中
    navChange = (e) => {
        this.state.navList.forEach((item) => {
            if (e.nav !== "筛选") {
                item.isSelected = (item.title === e.nav)
            }

        })
        var priceCli = 0;
        // let isScreen = false
        switch (e.nav) {

            case "综合":
                this.state.thisGoodsList.sort(this.down('SigoPrice'));
                break;
            case "价格":
                let excClick = this.state.priceCli
                if (excClick === 0) {
                    priceCli = 1
                    this.state.thisGoodsList.sort(this.up('ItemPriceStr'));
                } else if (excClick === 1) {
                    priceCli = 2
                    this.state.thisGoodsList.sort(this.down('ItemPriceStr'));
                } else if (excClick === 2) {
                    priceCli = 1
                    this.state.thisGoodsList.sort(this.up('ItemPriceStr'));

                }

                break;
            case "销量":
                this.state.thisGoodsList.sort(this.up('SigoPrice'));
                break;
            case "筛选":
                this.setState({

                    isScreen: !this.state.isScreen
                })
                break;
            default:
                break;
        }

        this.setState({
            navList: this.state.navList,
            priceCli: priceCli
        })
    }
    // 筛选
    screenChange = (e, event) => {
        // console.log(e)
        // 阻止事件冒泡
        const ev = event || window.event;
        ev.stopPropagation();
        ev.nativeEvent.stopImmediatePropagation();
        switch (e.par) {
            // 一级筛选标题
            case "ONE":
                this.state.screenData.forEach((item) => {
                    if (item.id === e.id) {
                        item.isChange = !item.isChange
                    }
                })
                this.setState({
                    screenData: this.state.screenData
                })
                break;
            // 二级筛选标题
            case "TOW":
                // console.log
                this.state.screenData.forEach((item) => {
                    if (item.id === e.id) {
                        item.content.forEach((items) => {
                            if (items.title === e.title) {
                                items.isChange = !items.isChange
                            }
                        })
                    }
                })

                this.setState({
                    screenData: this.state.screenData,
                })

                break;
            // 重置
            case "CLEAR":
                this.state.screenData.forEach((item) => {
                    item.content.forEach((items) => {
                        items.isChange = false
                    })
                    // item.isChange = false;
                })
                this.setState({
                    screenData: this.state.screenData
                })
                break;
            // 隐藏
            case "HIDE":
                this.setState({
                    isScreen: !this.state.isScreen
                })
                break;
            // 筛选
            case "SCR":
                this.setState({
                    isScreen: !this.state.isScreen
                })
                break;
            default:
                break;
        }
    }
   

    // 清空搜索框
    clearSearch = () => {
        this.setState({
            searchValue: ""
        })
    }
    // input框数据双向绑定
    inputValChange = (e) => {
        this.setState({
            searchValue: e.target.value
        })
    }

    // 返回上一页
    goBack = () => {
        back()
    }
    // 返回顶部
    scrollToAnchor = (anchorName) => {
        if (anchorName) {
            let anchorElement = document.getElementById(anchorName);
            if (anchorElement) { anchorElement.scrollIntoView(); }
        }
    }
    // 滚动条监听
    bindHandleScroll = () => {
        // console.log(e)
        // let clientHeight = document.documentElement.clientHeight; //可视区域高度
        let scrollTop = document.documentElement.scrollTop;  //滚动条滚动高度
        // let scrollHeight = document.documentElement.scrollHeight; //滚动内容高度

        // console.log(clientHeight, scrollTop, scrollHeight)
        if (scrollTop < 10) {
            this.setState({
                headerTop: true
            })
        } else if (scrollTop >= 100) {
            this.setState({
                headerTop: false
            })
        }

    }
    componentDidMount = () => {
        // 添加滚动监听
        window.addEventListener('scroll', this.bindHandleScroll)

        // console.log(this.props.location.state)
        if (this.props.location.state) {
            this.setState({
                searchValue: this.props.location.state.title
            })
            // 获取筛选数据
            CategoryServer.getCategoryData("/data/screenData.json", 1).then((data) => {
                // console.log(data)
                this.setState({
                    screenData: data
                })
            }).catch((error) => {
                console.log(error)
            })

            let goodsList = []
            let excGoodsList = []
            if (JSON.stringify(this.props.homeData) === "{}") {
                HomeServer.getHomeData("/data/homeData.json", 1).then((data) => {
                    // console.log(data)

                    let action = {
                        type: "HOME_DATA",
                        data: data || {}
                    }
                    // 调用dispatch
                    this.props.dispatch(action)

                    goodsList = data.pageRes || []
                    // 数据初步筛选

                    goodsList.forEach((item) => {
                        excGoodsList = [...excGoodsList, ...item.arrValue]
                    })
                    // 过滤可用数据
                    let screenGoodisList = []
                    screenGoodisList = excGoodsList.filter((item) => {
                        return item.ItemTitle.indexOf(this.props.location.state.title) !== -1
                    })
                    // console.log(excGoodsList)
                    this.setState({
                        thisGoodsList: screenGoodisList,
                        typeGoodsList: screenGoodisList
                    })
                }).catch((error) => {
                    console.log(error)
                })
            } else {
                goodsList = this.props.homeData.pageRes;
                // 数据初步筛选
                goodsList.forEach((item) => {
                    excGoodsList = [...excGoodsList, ...item.arrValue]
                })
                // 过滤可用数据
                let screenGoodisList = []
                screenGoodisList = excGoodsList.filter((item) => {
                    return item.ItemTitle.indexOf(this.props.location.state.title) !== -1
                })
                // console.log(excGoodsList)
                this.setState({
                    thisGoodsList: screenGoodisList,
                    typeGoodsList: screenGoodisList
                })
            }

        } else {
            this.props.history.push("/cateGory")
        }
    }
    /* 降序 */
    down(name) {
        return function (obj1, obj2) {
            let val1 = obj1[name];
            let val2 = obj2[name];
            return val2 - val1;
        };
    }
    /* 升序 */
    up(name) {
        return function (obj1, obj2) {
            let val1 = obj1[name];
            let val2 = obj2[name];
            return val1 - val2;
        };
    }
    componentWillUnmount() {
        window.removeEventListener('scroll', this.bindHandleScroll);
        // 卸载异步操作设置状态
        this.setState = (state, callback) => {
            return;
        }
    }
}
export default connect(state => {
    return { homeData: state.homeData }
})(withRouter(CategoryT));